package postgres

import (
	"context"
	"quipus/internal/database/model"

	apb "quipus/proto/gen/assist"

	_ "github.com/jackc/pgx/v5/stdlib"
	_ "github.com/joho/godotenv/autoload"
	"gorm.io/gorm/clause"
)

func (p *PGDB) UpsertReaction(ctx context.Context, upsert *model.Reaction) error {
	p.query()
	qdo := q.WithContext(ctx)
	err := qdo.Reaction.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "knot_id"}, {Name: "reaction_type"}, {Name: "creator_id"}},
		DoUpdates: clause.AssignmentColumns([]string{"knot_id", "reaction_type", "creator_id"}),
	}).Create(upsert)
	if err != nil {
		return err
	}

	return nil
}

func (p *PGDB) ListReactions(ctx context.Context, find *apb.FindReaction) ([]*model.Reaction, error) {
	p.query()
	reaction := q.WithContext(ctx).Reaction
	if find.KnotId > 0 {
		reaction = reaction.Where(q.Reaction.KnotID.Eq(find.KnotId))
	}
	if find.CreatorId > 0 {
		reaction = reaction.Where(q.Reaction.CreatorID.Eq(find.CreatorId))
	}

	if find.Id > 0 {
		reaction = reaction.Where(q.Reaction.ID.Eq(find.Id))
	}

	return reaction.Find()
}

func (p *PGDB) DeleteReaction(ctx context.Context, delete *apb.DeleteReaction) error {
	p.query()
	reaction := q.WithContext(ctx).Reaction
	if delete.Id > 0 {
		reaction = reaction.Where(q.Reaction.ID.Eq(delete.Id))
	}

	if delete.KnotId > 0 {
		reaction = reaction.Where(q.Reaction.KnotID.Eq(delete.KnotId))
	}
	if delete.Action != "" {
		reaction = reaction.Where(q.Reaction.ReactionType.Eq(delete.Action))
	}
	_, err := reaction.Delete()

	return err
}
